package cn.hxh.listener;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

/**
 * @Author: HongXiaoHan
 * @Description
 * @Date: 2020/8/21 13:06
 */
public class MyListener implements HttpSessionListener {
    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext servletContext = se.getSession().getServletContext();
        Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");

        System.out.println(se.getSession().getId());
        if (onlineCount == null) {
            onlineCount = 1;
        } else {
            onlineCount = onlineCount + 1;
        }
        servletContext.setAttribute("OnlineCount", onlineCount);
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext servletContext = se.getSession().getServletContext();
        Integer onlineCount = (Integer) servletContext.getAttribute("OnlineCount");
        onlineCount = onlineCount - 1;
        servletContext.setAttribute("OnlineCount", onlineCount);

    }
}
